#ifndef __CHATSERVICE_H_
#define __CHATSERVICE_H_

#include "usermodel.hpp"
#include "offlinemessagemodel.hpp"
#include "friendmodel.hpp"
#include "groupmodel.hpp"
#include "redis.hpp"
#include "PCHAT.pb.h"

#include <unordered_map>
#include <functional>
#include <muduo/net/TcpConnection.h>
#include <mutex>

using namespace muduo;
using namespace muduo::net;
using namespace std;

using MsgHandler = std::function<bool(const TcpConnectionPtr&,
	const ChatMessage&,
	const Timestamp&)>;

//聊天服务器业务类
class ChatService {
public:
	static ChatService& getInstance();

	bool login(const TcpConnectionPtr&, const ChatMessage&, const Timestamp&);
	bool reg(const TcpConnectionPtr&, const ChatMessage&, const Timestamp&);
	bool oneChat(const TcpConnectionPtr&, const ChatMessage&, const Timestamp&);
	bool addFriend(const TcpConnectionPtr&, const ChatMessage&, const Timestamp&);
	bool createGroup(const TcpConnectionPtr& conn, const ChatMessage&, const Timestamp&);
	bool addGroup(const TcpConnectionPtr& conn, const ChatMessage&, const Timestamp&);
	bool groupChat(const TcpConnectionPtr& conn, const ChatMessage&, const Timestamp&);
	bool loginOut(const TcpConnectionPtr& conn, const ChatMessage&, const Timestamp&);

	//服务器异常后，业务重置方法
	void reset();

	//获取消息对应的处理器
	MsgHandler getHandler(int msgid);

	//处理客户端异常退出
	void clientCloseException(const TcpConnectionPtr& conn);

	//从redis消息队列中获取订阅的消息
	void handleRedisSubscribeMessage(int userid, string msg);

private:
	ChatService();

	//登录成功后，装载用户信息（好友列表，离线消息，群聊列表）
	void setUserInfo(LoginResponse* login_response, P_User* user_info, User& user);
	inline void setUserStateOnline(User& user);
	inline void setUserStateOffline(User& user);

	//<消息id，对应的处理操作>
	unordered_map<int, MsgHandler> m_msgHandlerMap;
	//存储在线用户的连接的容器
	unordered_map<int, TcpConnectionPtr> m_userConnMap;

	//定义互斥锁，保证m_userConnMap访问的线程安全
	mutex m_connMutex;

	//数据操作类对象
	UserModel m_userModel;
	OfflineMsgModel m_offlineMessageModel;
	FriendModel m_friendModel;
	GroupModel m_groupModel;

	//redis操作对象
	Redis m_redis;
};

#endif // !__CHATSERVICE_H_